package persistence;

import beans.Usuario;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;



public class DAOUsuario {
    private EntityManager em;

    public DAOUsuario(EntityManager em) {
        this.em = em;
    }
    public String criptografaSenha (String senha) throws NoSuchAlgorithmException {  
        MessageDigest md = MessageDigest.getInstance("MD5");  
        BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));  
        String s = hash.toString(16);  
        if (s.length() %2 != 0)  
            s = "0" + s;  
        return s;  
    }
    
    public Usuario BuscaLoginSenha(String email){
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        Root<Usuario> rUser = cq.from(Usuario.class);
        cq.select(rUser);
        cq.where(cb.equal(rUser.get("login"), email));
        
        Query q = (Query) em.createQuery(cq);
        
        Usuario user = null;
        try {
            user = (Usuario) q.getSingleResult();
        } catch (NoResultException e) {
            
        }
        
        return user;
    }
}
